import utils.DBUtil as db
from DrissionPage import ChromiumPage
import utils.DateUtil as date
import time


def do_analysis(code, name):
    url = "https://stockpage.10jqka.com.cn/" + code + "/"
    try:
        page.get(url)
        # {id:'xx','username':'xxx',password:'xxxx'}

        base_info = page.ele(".company_details").text
        contents = base_info.split("\n")
        area = contents[1]
        list_date = contents[8]
        per_net = float(contents[10].replace("元", ""))  # 每股净资产
        per_income = float(contents[12].replace("元", ""))  # 每股收益
        if "万" in contents[14]:
            net_profit = float(contents[14].replace("万元", ""))
        elif "亿" in contents[14]:
            net_profit = float(contents[14].replace("亿元", "")) * 1000
        else:
            net_profit = float(contents[14].replace("元", "")) / 1000

        growth_rate = float(contents[16].replace("%", ""))  # 增长率

        if "万" in contents[18]:
            trade_income = float(contents[18].replace("万元", ""))
        elif "亿" in contents[18]:
            trade_income = float(contents[18].replace("亿元", "")) * 1000
        else:
            trade_income = float(contents[18].replace("元", "")) / 1000

        per_cash = float(contents[20].replace("元", ""))  # 每股现金流
        per_fund = float(contents[22].replace("元", ""))  # 每股公积金
        per_undistribute_profit = float(contents[24].replace("元", ""))  # 每股未分配利润

        if "万" in contents[26]:
            total_equity = float(contents[26].replace("万", "")) / 1000
        else:
            total_equity = float(contents[26].replace("亿", ""))

        if "万" in contents[28]:
            total_circulate = float(contents[28].replace("万", "")) / 1000
        else:
            total_circulate = float(contents[28].replace("亿", ""))

        score_info = page.ele(".fl analyze-result clearfix").text.split("\n")
        base_score = score_info[0]
        ts_str = base_score[0: base_score.index('综合')]
        if ts_str == '--':
            ts_str = -1

        total_score = float(ts_str)
        ds_str = base_score[base_score.index('打败了') + 3: base_score.index('%')]
        if ds_str == '--':
            ds_str = -1
        defeat_score = float(ds_str)
        short_trend = score_info[2]
        medium_trend = score_info[4]
        long_trend = score_info[6]
        total_desc = score_info[7]

        ana_score = page.ele(".analyze-level fr").text.split("\n")
        technical_score = float(ana_score[0][ana_score[0].index("诊股") + 2:])
        fund_score = float(ana_score[1][ana_score[1].index("诊股") + 2:])
        message_score = float(ana_score[2][ana_score[2].index("诊股") + 2:])
        industry_score = float(ana_score[3][ana_score[3].index("诊股") + 2:])
        base_face_score = float(ana_score[4][ana_score[4].index("诊股") + 2:])

        # 拼装数据
        insert_sql = "INSERT INTO `stock`.`base_info` (`code`, `name`, `area`, `list_date`, `per_net`, `per_income`, `net_profit`, `growth_rate`, `trade_income`, `per_cash`, `per_fund`, `per_undistribute_profit`, `total_equity`, `total_circulate`, `d_date`, `total_score`, `defeat_score`, `short_trend`, `medium_trend`, `long_trend`, `total_desc`, `technical_score`, `fund_score`, `message_score`, `industry_score`, `base_score`) VALUES ({},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{})".format(
            "'" + code + "'",
            "'" + name + "'",
            "'" + area + "'",
            "'" + list_date + "'",
            per_net,
            per_income,
            net_profit,
            growth_rate,
            trade_income,
            per_cash,
            per_fund,
            per_undistribute_profit,
            total_equity,
            total_circulate,
            "'2023-12-08'",
            total_score,
            defeat_score,
            "'" + short_trend + "'",
            "'" + medium_trend + "'",
            "'" + long_trend + "'",
            "'" + total_desc + "'",
            technical_score,
            fund_score,
            message_score,
            industry_score,
            base_face_score
        )

        print('insert_sql=' + insert_sql)

        conn = db.connect_db()
        cursor = conn.cursor()
        cursor.execute(insert_sql)
        conn.commit()
        conn.close()
    except IndexError as e:
        print(e)


page = ChromiumPage()
sql = "SELECT d_code,d_name FROM stock_info WHERE d_code NOT LIKE '43%' AND d_code NOT LIKE '8%' AND d_code NOT LIKE '68%' AND d_code NOT LIKE '4%' AND d_name NOT LIKE '%ST%' and id >= 3347 and id <=4479"
dataList = db.get_data(sql)

for data in dataList:
    code = data[0]
    name = data[1]
    # print(code, name)
    do_analysis(code, name)
    time.sleep(1)  # 休眠1秒
